package com.easycms.web.system.service;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.easycms.common.IdHelper;
import com.easycms.framework.domain.DataTableDto;
import com.easycms.enums.DataStatusEnum;
import com.easycms.framework.domain.ResultAdaptDto;
import com.easycms.framework.exception.EasyException;
import com.easycms.framework.shiro.UserOwnInfo;
import com.easycms.web.system.domain.SysDept;
import com.easycms.web.system.domain.SysRole;
import com.easycms.web.system.domain.SysUser;
import com.easycms.web.system.domain.SysUserPosition;
import com.easycms.web.system.mapper.SysDeptMapper;
import com.easycms.web.system.mapper.SysRoleMapper;
import com.easycms.web.system.mapper.SysUserMapper;
import com.easycms.web.system.mapper.SysUserPositionMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Service
public class SysUserService {

    @Autowired
    private SysUserMapper userMapper;
    @Autowired
    private SysRoleMapper roleMapper;
    @Autowired
    private SysDeptMapper deptMapper;
    @Autowired
    private SysUserPositionMapper userPositionMapper;
    /**
    *
     * @author yushuo
     * @description //登录
     * @date 13:47 2021/2/4
     * @param [loginName, password]
     * @return com.easycms.web.system.domain.SysUser
    **/
    public SysUser login(String loginName){
        LambdaQueryWrapper<SysUser> query=new LambdaQueryWrapper<>();
        query.eq(SysUser::getLoginName,loginName)
        .last("limit 1");
        SysUser user= userMapper.selectOne(query);
        return user;
    }

    /**
    *
     * @author yushuo
     * @description //用户列表
     * @date 15:01 2021/1/29
     * @param
     * @return com.easycms.framework.domain.DataTableDto
    **/
    public DataTableDto getUserList(DataTableDto dto,String loginName,String userName,String phone){
        LambdaQueryWrapper<SysUser> query=new LambdaQueryWrapper<>();
        if(!StrUtil.isEmpty(loginName)){
            query.like(SysUser::getLoginName,loginName.trim());
        }
        if(!StrUtil.isEmpty(userName)){
            query.like(SysUser::getUserName,userName.trim());
        }
        if(!StrUtil.isEmpty(phone)){
            query.like(SysUser::getMobilePhone,phone.trim());
        }
        //分页查询
        query.orderByDesc(SysUser::getIsSuper,SysUser::getCreateTime);
        Page<SysUser> page = new Page<>(dto.getPageNumber(), dto.getPageSize());
        IPage<SysUser> userIPage = userMapper.selectPage(page, query);
        List<SysUser> userList=userIPage.getRecords();
        //获取用户的角色信息
        List<Long> roleIds=userList.stream().filter(u->u.getRoleId()>0).map(u->u.getRoleId()).distinct().collect(Collectors.toList());
        List<SysRole> roles=getRoleByIds(roleIds);

        if(roles!=null&&roles.size()>0){
            userList.stream().forEach(u->{
                Long roleId=u.getRoleId();
                Optional<SysRole> role=roles.stream().filter(r->r.getId().equals(roleId)).findFirst();
                if(role.isPresent()){
                    u.setRoleName(role.get().getRoleName());
                }
            });
        }
        dto.setTotal(userIPage.getTotal());
        dto.setRows(userList);
        return dto;
    }

    /**
    *
     * @author yushuo
     * @description //获取角色信息
     * @date 14:40 2021/2/2
     * @param [roleIds]
     * @return java.util.List<com.easycms.web.system.domain.SysRole>
    **/
    private List<SysRole> getRoleByIds(List<Long> roleIds){
        if(roleIds.size()>0){
            LambdaQueryWrapper<SysRole> query=new LambdaQueryWrapper<>();
            query.in(SysRole::getId,roleIds)
            .select(SysRole::getId,SysRole::getRoleName);
            List<SysRole> roles=roleMapper.selectList(query);
            return roles;
        }
        return null;
    }
    /**
    *
     * @author yushuo
     * @description //判断用户名是否存在
     * @date 10:39 2021/2/1
     * @param dto
     * @return boolean
    **/
    public boolean userExists(SysUser dto){
        LambdaQueryWrapper<SysUser> query=new LambdaQueryWrapper<>();
        query.eq(SysUser::getLoginName,dto.getLoginName())
                .select(SysUser::getId, SysUser::getLoginName)
                .last("limit 1");
        SysUser user=userMapper.selectOne(query);
        if(user==null){
            return false;
        }
        if(user.getId().equals(dto.getId())){
            return false;
        }
        return true;

    }
    /**
    *
     * @author yushuo
     * @description //保存用户
     * @date 10:28 2021/2/1
     * @param dto
     * @return void
    **/

    @Transactional(rollbackOn = EasyException.class)
    public void save(SysUser dto,String[] positions, UserOwnInfo userOwnInfo){
          if(dto.getUserStatus()==0){
              dto.setUserStatus(DataStatusEnum.DISABLE.getCode());
          }else{
              dto.setUserStatus(DataStatusEnum.ENABLE.getCode());
          }
        if(dto.getIsSuper()==0){
            dto.setIsSuper(DataStatusEnum.NOT_SUPER.getCode());
        }else{
            dto.setIsSuper(DataStatusEnum.SUPER.getCode());
        }


        if(dto.getDeptId()==null||dto.getDeptId()==0){
            dto.setDeptId(0);
            dto.setDeptName("");
        }else{
            SysDept dept=deptMapper.selectById(dto.getDeptId());
            if(dept!=null){
                dto.setDeptName(dept.getDeptName());
            }
        }
        if(dto.getRoleId()==null){
            dto.setRoleId(0L);
        }


        if(StrUtil.isEmpty(dto.getUserAvatar())){
            dto.setUserAvatar("/img/profile.jpg");
        }
        dto.setUpdateTime(DateUtil.date());
        dto.setUpdateBy(userOwnInfo.getLoginName());
        if(dto.getId()==0){
            dto.setId(IdHelper.nextId());
            dto.setDelFlag(DataStatusEnum.NOT_DELETED.getCode());
            dto.setCreateBy(userOwnInfo.getLoginName());
            dto.setCreateTime(DateUtil.date());
            userMapper.insert(dto);
        }else{
            SysUser user=userMapper.selectById(dto.getId());
            if(user!=null){
                dto.setDelFlag(user.getDelFlag());
                userMapper.updateById(dto);
            }
        }

        //插入职位信息
        LambdaQueryWrapper<SysUserPosition> userPLambda=Wrappers.lambdaQuery();
        userPLambda.eq(SysUserPosition::getUserId,dto.getId());
        userPositionMapper.delete(userPLambda);
        if(positions.length>0){
            for (String positionId:positions){
                SysUserPosition userPostion=new SysUserPosition();
                userPostion.setUserId(dto.getId());
                userPostion.setPositionId(Convert.toLong(positionId));
                userPostion.setCreateBy(userOwnInfo.getLoginName());
                userPostion.setCreateTime(dto.getUpdateTime());
                userPositionMapper.insert(userPostion);
            }
        }
    }


    /**
    *
     * @author yushuo
     * @description 获取用户信息
     * @date 13:48 2021/2/1
     * @param id
     * @return com.easycms.web.system.domain.SysUser
    **/
    public SysUser getModel(Long id){
        SysUser user= userMapper.selectById(id);
        if(user!=null){
            LambdaQueryWrapper<SysUserPosition> userPLambda=Wrappers.lambdaQuery();
            userPLambda.eq(SysUserPosition::getUserId,id)
            .select(SysUserPosition::getPositionId);
            List<Long> userPostions=userPositionMapper.selectList(userPLambda).stream().map(SysUserPosition::getPositionId).collect(Collectors.toList());
            user.setPositionList(userPostions);
        }

        return user;
    }

    /**
    *
     * @author yushuo
     * @description //删除数据
     * @date 15:39 2021/1/29
     * @param
     * @return void
    **/
    public void removeAll(String ids){
        List<Long> idArray = Arrays.asList(Convert.toLongArray(ids)) ;
        userMapper.deleteBatchIds(idArray);

    }

    /**
    *
     * @author yushuo
     * @description 更新个人资料
     * @date 11:20 2021/2/27
     * @param [id, userName, mobilePhone, email, gender]
     * @return com.easycms.framework.domain.ResultAdaptDto
    **/
    public ResultAdaptDto updateProfile(long id,String userName,String mobilePhone,String email,int gender)
    {
        ResultAdaptDto ret=new ResultAdaptDto();
        SysUser user=userMapper.selectById(id);
        if(user==null){
            ret.setMessage("用户不存在");
            ret.setStatus(false);
            return ret;
        }

        LambdaUpdateWrapper<SysUser> update= Wrappers.lambdaUpdate();
        update.set(SysUser::getUserName,userName)
                .set(SysUser::getMobilePhone,mobilePhone)
                .set(SysUser::getEmail,email)
                .set(SysUser::getGender,gender)
                .eq(SysUser::getId,id);
        userMapper.update(null,update);
        ret.setMessage("个人信息已更新");
        return ret;
    }

     /**
     *
      * @author yushuo
      * @description 更新密码
      * @date 11:21 2021/2/27
      * @param [id, oldPassword, newPassword]
      * @return com.easycms.framework.domain.ResultAdaptDto
     **/
    public ResultAdaptDto updatePassword(Long id,String accountName, String oldPassword, String newPassword){
        ResultAdaptDto ret=new ResultAdaptDto();
        SysUser user=userMapper.selectById(id);
        if(user==null){
            ret.setMessage("用户不存在");
            ret.setStatus(false);
            return ret;
        }
        if(StrUtil.isEmpty(accountName)){
            if(!user.getPassWord().equals(oldPassword)){
                ret.setMessage("密码比对失败，禁止更新");
                ret.setStatus(false);
                return ret;
            }
        }

        LambdaUpdateWrapper<SysUser> update= Wrappers.lambdaUpdate();
        update.set(SysUser::getPassWord,newPassword)
        .eq(SysUser::getId,id);
        userMapper.update(null,update);
        ret.setMessage("密码更新成功");
        return ret;
    }
}
